package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {

    //2025.1.1.01:01:01时间戳
    public static final Long BEGIN_TIMESTAMP =  1735693261L;
    //序列号长度
    public static final int NUM_BITS = 32;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //获取全局唯一ID
    public Long getID(String keyPrefix){
        //1.生成当前时间戳
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = nowSecond - BEGIN_TIMESTAMP;

        //2.生成序列号
        //2.1获取当前时间
        String format = now.format(DateTimeFormatter.ofPattern("yyyyMMdd"));

        Long count = stringRedisTemplate.opsForValue().increment("icr:" + keyPrefix + ":" + format);

        return timestamp << NUM_BITS | count;
    }


}
